public class StringBuilderVsStringBuffer {

    public static void main(String[] args) {
        String stringToAppend = "test";
        int numberOfAppends = 100000;

        long startTimeBuilder = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numberOfAppends; i++) {
            sb.append(stringToAppend);
        }
        long endTimeBuilder = System.currentTimeMillis();
        long durationBuilder = endTimeBuilder - startTimeBuilder;

        long startTimeBuffer = System.currentTimeMillis();
        StringBuffer sbf = new StringBuffer();
        for (int i = 0; i < numberOfAppends; i++) {
            sbf.append(stringToAppend);
        }
        long endTimeBuffer = System.currentTimeMillis();
        long durationBuffer = endTimeBuffer - startTimeBuffer;

        System.out.println("StringBuilder 拼接时间: " + durationBuilder + " 毫秒");
        System.out.println("StringBuffer 拼接时间: " + durationBuffer + " 毫秒");

        if (durationBuilder < durationBuffer) {
            System.out.println("StringBuilder 比 StringBuffer 快。");
        } else if (durationBuilder > durationBuffer) {
            System.out.println("StringBuffer 比 StringBuilder 快。");
        } else {
            System.out.println("StringBuilder 和 StringBuffer 速度相同。");
        }
    }
}

